package com.zhijiaoyun.controller.api;

import com.zhijiaoyun.common.CommonUtils;
import com.zhijiaoyun.common.DsConstant;
import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.controller.base.BaseController;
import com.zhijiaoyun.model.*;
import com.zhijiaoyun.model.dto.*;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Controller
@RequestMapping(value = "/api/course", produces = "application/json; charset=utf-8")
public class CourseApi extends BaseController {

    @ResponseBody
    @RequestMapping(value = "/getAllCategory", method = RequestMethod.GET)
    public Map<String, Object> getAllCategory() {
        Map<String, Object> map = new HashedMap<>();

        List<CourseCategoryDto> categoryDto = new ArrayList<>();
        List<CourseCategory> categorys = courseCategoryService.getCourseCategoryByParentId(0L);

        if (!StringUtils.isEmptyList(categorys)) {
            for (CourseCategory courseCategory : categorys) {
                CourseCategoryDto courseCategoryDto = new CourseCategoryDto(courseCategory);
                List<CourseCategory> second = courseCategoryService
                        .getCourseCategoryByParentId(courseCategory.getCategoryId());
                if (!StringUtils.isEmptyList(second)) {
                    courseCategoryDto.setSubCategory(second);
                } else {
                    courseCategoryDto.setSubCategory(new ArrayList<>());
                }
                categoryDto.add(courseCategoryDto);
            }
        }
        map.put("list", categoryDto);

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/{parentId}/getCategory", method = RequestMethod.GET)
    public Map<String, Object> getCategory(@PathVariable("parentId") Long parentId) {
        Map<String, Object> map = new HashMap<>();
        List<CourseCategory> categorys = courseCategoryService.getCourseCategoryByParentId(parentId);
        map.put("list", categorys);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/getRecommend", method = RequestMethod.GET)
    public Map<String, Object> getRecommend() {
        Map<String, Object> map = new HashedMap<>();

        List<CourseRecommendDto> courseDto = new ArrayList<>(CAPACITY_4);

        // 找到所有的推荐课程
        List<CourseRecommendDto> courses = courseRecommendService.getCourseRecommentByParamsDto();

        if (!StringUtils.isEmptyList(courses)) {
            if (courses.size() > DsConstant.RECOMMEND_LIMIT_SIZE) {
                // 随机生成四个数字
                Collections.shuffle(courses);
                courseDto.addAll(courses.subList(0, 4));
            } else {
                courseDto.addAll(courses);
            }
        } else {
            courseDto.addAll(new ArrayList<>());
        }

        map.put("list", courseDto);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/{type}/higherEdu", method = RequestMethod.GET)
    public Map<String, Object> higherEdu(@PathVariable("type") Integer type) {
        Map<String, Object> map = new HashedMap<>();

        // 高职教模块，去每个分类下面的 （一轮复习，百日冲刺两个分类下的数据，只需要两条数据）
        // 语文，数学，财会，机械，计算机，外贸，旅游，商业，电子电工
        // 找到每个分类下，一轮复习，百日冲刺的id
        // 语文

        List<CourseSpecialDto> courseSpecialDtos = new ArrayList<>();
        int size = 2;
        boolean isHigerEdu = true;
        if (type != null && type == 1) {
            size = 4;
            isHigerEdu = false;
        }

        CourseSpecialDto chineseSpecialDto = getSpecialCourse("语文", size, isHigerEdu);
        CourseSpecialDto mathSpecialDto = getSpecialCourse("数学", size, isHigerEdu);
        CourseSpecialDto accountSpecialDto = getSpecialCourse("财会", size, isHigerEdu);
        CourseSpecialDto mechaincalSpecialDto = getSpecialCourse("机械", size, isHigerEdu);
        CourseSpecialDto computerSpecialDto = getSpecialCourse("计算机", size, isHigerEdu);
        CourseSpecialDto tradeSpecialDto = getSpecialCourse("外贸", size, isHigerEdu);
        CourseSpecialDto tourSpecialDto = getSpecialCourse("旅游", size, isHigerEdu);
        CourseSpecialDto businessSpecialDto = getSpecialCourse("商业", size, isHigerEdu);
        CourseSpecialDto electronSpecialDto = getSpecialCourse("电子电工", size, isHigerEdu);
        courseSpecialDtos.add(chineseSpecialDto);
        courseSpecialDtos.add(mathSpecialDto);
        courseSpecialDtos.add(accountSpecialDto);
        courseSpecialDtos.add(mechaincalSpecialDto);
        courseSpecialDtos.add(tradeSpecialDto);
        courseSpecialDtos.add(businessSpecialDto);
        courseSpecialDtos.add(electronSpecialDto);
        courseSpecialDtos.add(tourSpecialDto);
        courseSpecialDtos.add(computerSpecialDto);

        map.put("list", courseSpecialDtos);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/courseList", method = RequestMethod.POST)
    public Map<String, Object> courseList(Integer pageIndex, Integer pageSize, String name, String title, Long category1, Long category2) {
        Map<String, Object> map = new HashMap<>();

        List<Long> ids = new ArrayList<>();
        // 接口这边 category1 和 category2只会传一个值
        if (category1 != null) {
            ids = courseCategoryService.getIdsByParentId(category1);
        } else if (category2 != null) {
            ids.add(category2);
        }

        PageList<CourseDto> courses = courseService.pageByParamsDto(pageIndex, pageSize == null ? DsConstant.PAGE_SIZE_12 : pageSize, name, title, -1, ids);

        map.put("list", courses.getList());
        map.put("page", courses.getPageData());

        return map;
    }

    /**
     * 课程详情
     *
     * @param courseId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/courseInfo", method = RequestMethod.GET)
    public Map<String, Object> courseDetail(@PathVariable(value = "courseId") Long courseId) {
        // 添加浏览记录
        CourseView courseView = new CourseView(courseId, 1, 0L, "");
        courseViewService.addCourseView(courseView);
        courseService.addViewNum(courseId);
        return courseService.getById(courseId);
    }

    @ResponseBody
    @RequestMapping(value = "/{lessonId}/lessonInfo", method = RequestMethod.POST)
    public Map<String, Object> lessonDetail(@PathVariable("lessonId") Long lessonId, String token) {
        Map<String, Object> map = new HashMap<>();
        Long userId = CommonUtils.getUserIdByToken(token);
        if (userId == 0) {
            map.put(DsConstant.CODE, DsConstant.CODE_TOKEN_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_TOKEN_LOST);
            return map;
        }

        // 通过userid lesson.getCourseId()找购买记录
        Lesson lesson = lessonService.getLessonByLessonId(lessonId);
        if (lesson != null) {
            Course course = courseService.getCourseByCourseId(lesson.getCourseId());
            if (course != null && course.getCurrentPrice().intValue() > 0) {
                BuyHistory buy = buyHistoryService.getBuyHistoryByUserIdGoodsId(userId, lesson.getCourseId(), 1);
                if (buy == null) {
                    map.put(DsConstant.CODE, DsConstant.CODE_BUY_NOTYET);
                    map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_BUY_NOTYET);
                    return map;
                }
            }

        }

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        map.put("obj", lesson);
        return map;
    }

    /**
     * 课时详情
     *
     * @param courseId
     * @param name
     * @param title
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/lessonList", method = RequestMethod.POST)
    public Map<String, Object> lessonList(@PathVariable("courseId") Long courseId, String name, String title) {
        return lessonService.listByParams(courseId, name, title);
    }

    private CourseSpecialDto getSpecialCourse(String categoryName, int size, boolean isHigerEdu) {
        CourseSpecialDto chineseSpecialDto = new CourseSpecialDto();
        chineseSpecialDto.setCategoryName(categoryName);
        CourseCategory chinese = courseCategoryService.getCourseCategoryByName(categoryName);
        if (chinese != null) {
            List<Long> chineseIds = courseCategoryService.getSpecialIdsByParentId(chinese.getCategoryId(), isHigerEdu);
            if (!StringUtils.isEmptyList(chineseIds)) {
                List<CourseDto> chineseDtos = courseService.getCourseByCategoryIds(chineseIds, size);
                if (!StringUtils.isEmptyList(chineseDtos)) {
                    if (chineseDtos.size() > size) {
                        chineseSpecialDto.setCourseDto(chineseDtos.subList(0, size));
                    } else {
                        chineseSpecialDto.setCourseDto(chineseDtos);
                    }
                } else {
                    chineseSpecialDto.setCourseDto(new ArrayList<>());
                }
            }
        }
        return chineseSpecialDto;
    }

    private CourseSpecialDto getSpecialCourse(String categoryName, int size, int type) {
        CourseSpecialDto specialDto = new CourseSpecialDto();
        specialDto.setCategoryName(categoryName);
        CourseCategory chinese = courseCategoryService.getCourseCategoryByName(categoryName);
        if (chinese != null) {
            List<Long> chineseIds = courseCategoryService.getSpecialIdsByParentIdType(chinese.getCategoryId(), type);
            if (!StringUtils.isEmptyList(chineseIds)) {
                List<CourseDto> chineseDtos = courseService.getCourseByCategoryIds(chineseIds, size);
                if (!StringUtils.isEmptyList(chineseDtos)) {
                    if (chineseDtos.size() > size) {
                        specialDto.setCourseDto(chineseDtos.subList(0, size));
                    } else {
                        specialDto.setCourseDto(chineseDtos);
                    }
                } else {
                    specialDto.setCourseDto(new ArrayList<>());
                }
            }
        }
        return specialDto;
    }

    @ResponseBody
    @RequestMapping(value = "higherEdu/{type}", method = RequestMethod.GET)
    public Map<String, Object> higherEdu(@PathVariable("type") Integer type, Integer pageSize, String subjectName) {
        Map<String, Object> map = new HashedMap<>();
        /**
         * type :
         * 0:全部
         * 1:一轮复习
         * 2:白日冲刺
         * 3:非一轮复习和百日冲刺
         */

        int size = (pageSize == null || pageSize <= 0) ? 6 : pageSize;

        CourseSpecialDto specialDto = getSpecialCourse(subjectName, size, type);

        map.put("obj", specialDto);
        return map;
    }

    /**
     * 评论
     *
     * @param courseId
     * @param message
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/comment", method = RequestMethod.POST)
    public Map<String, Object> comment(@PathVariable long courseId, String message, HttpServletRequest request) {
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        return courseService.comment(courseId, message, userId);
    }

    /**
     * 删除评论
     *
     * @param id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete-comment/{id}", method = RequestMethod.POST)
    public Map<String, Object> comment(@PathVariable long id, HttpServletRequest request) {
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        return courseService.deleteComment(id, userId);
    }

    /**
     * 某个课程的评论
     *
     * @param courseId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{courseId}/comments", method = RequestMethod.GET)
    public Map<String, Object> comments(@PathVariable long courseId, int pageIndex, int pageSize) {
        if (pageIndex <= 0) {
            pageIndex = 1;
        }
        if (pageSize <= 0) {
            pageSize = DsConstant.PAGESIZE_DEFAULT;
        }
        return courseService.listComments(pageIndex, pageSize, courseId);
    }

}
